﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using SmartHelper.ExtensionMethod;

namespace HttpHelper
{
    /// <summary>
    /// http帮助类，需要类库System.Net.Http
    /// </summary>
    public class HttpHelper
    {
        public static HttpClient httpClient = new HttpClient();

        public static WebClient webclient = new WebClient();

        public static void SetHttpClient(List<KeyValuePair<string,string>> arr)
        {
            if (arr!=null)
                foreach (var item in arr)
                {
                    httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
        }
        public static string Get(string uri, string encoding = "utf-8")
        {
            HttpResponseMessage response = httpClient.GetAsync(uri).Result;
            response.EnsureSuccessStatusCode();
            return Encoding.GetEncoding(encoding).GetString(response.Content.ReadAsByteArrayAsync().Result);
        }
        public static string Post(string uri, string json, string encoding = "utf-8", string mediaType = "application/json")
        {
            HttpContent httpContent = new StringContent(json, Encoding.GetEncoding(encoding), mediaType);
            HttpResponseMessage response = httpClient.PostAsync(uri, httpContent).Result;
            response.EnsureSuccessStatusCode();
            return response.Content.ReadAsStringAsync().Result;
        }

        public static string Post(string uri, List<KeyValuePair<String, String>> paramList, string encoding = "utf-8")
        {
            HttpResponseMessage response = httpClient.PostAsync(uri, new FormUrlEncodedContent(paramList)).Result;
            response.EnsureSuccessStatusCode();
            return Encoding.GetEncoding(encoding).GetString(response.Content.ReadAsByteArrayAsync().Result);
        }

        public static void SetCookie()
        {
            //httpClient.DefaultRequestHeaders.
        }
        /// <summary>
        /// 下载文件到指定的目录
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="filePath">文件夹路径</param>
        /// <returns>文件名</returns>
        public static string DownloadFileToDisk(string url,string filePath="d:\\AspnetDownload")
        {
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);
            string fileName = Path.GetFileName(url);
            fileName = fileName.Length > 50 ? Path.GetRandomFileName() : fileName;
            while (File.Exists(Path.Combine(filePath, fileName)))
                fileName = Path.GetRandomFileName();
            webclient.DownloadFile(url,Path.Combine(filePath ,fileName));
            return fileName;
        }
    }
}